<?php
declare (strict_types = 1);

namespace plugin\ky_black\app\admin\controller;

use plugin\ky_black\app\admin\model\BusinessPartner;
use plugin\ky_black\app\admin\model\BusinessType;
use support\Request;
use support\Response;
use think\facade\Db;

class BusinessPartnerController extends BaseController
{
    /**
     * 获取商家列表
     */
    public function list(Request $request)
    {
        $params = $request->get('params', []);
        $page = (int)($params['page'] ?? 1);
        $limit = (int)($params['limit'] ?? 10);

        $query = BusinessPartner::with(['businessType']);
        
        // 关键词搜索
        if (!empty($params['keyword'])) {
            $query->where(function($q) use ($params) {
                $q->where('name', 'like', "%{$params['keyword']}%")
                  ->orWhere('contact_phone', 'like', "%{$params['keyword']}%");
            });
        }
        
        // 商家类型筛选
        if (!empty($params['business_type_id'])) {
            $query->where('business_type_id', $params['business_type_id']);
        }
        
        // 状态筛选
        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }
        
        $total = $query->count();
        $list = $query->offset(($page - 1) * $limit)
                      ->limit($limit)
                      ->orderBy('partner_id', 'desc')
                      ->get();
        
        // 追加状态文本
        foreach ($list as $item) {
            $item->status_text = $item->status == 1 ? '启用' : '禁用';
            $item->business_type_name = $item->businessType->name ?? '';
            $item->service_level_text = $this->getServiceLevelText($item->service_level);
        }

        return $this->success([
            'list' => $list,
            'total' => $total
        ]);
    }

    /**
     * 获取所有选项数据
     */
    public function all(Request $request)
    {
        return $this->success([
            'business_types' => BusinessType::where('status', 1)
                ->orderBy('sort', 'asc')
                ->orderBy('id', 'asc')
                ->get(['id', 'name', 'code']),
            'service_levels' => [
                'vip' => 'VIP商家',
                'normal' => '普通商家'
            ],
            'status' => [
                1 => '启用',
                0 => '禁用'
            ]
        ]);
    }

    /**
     * 获取商家详情
     */
    public function detail(Request $request)
    {
        $params = $request->get('params', []);
        $partner_id = $params['partner_id'] ?? null;
        
        if (!$partner_id) {
            return $this->error('参数错误');
        }

        $partner = BusinessPartner::with(['businessType'])->find($partner_id);
        if (!$partner) {
            return $this->error('商家不存在');
        }

        $partner->status_text = $partner->status == 1 ? '启用' : '禁用';
        $partner->business_type_name = $partner->businessType->name ?? '';
        $partner->service_level_text = $this->getServiceLevelText($partner->service_level);

        return $this->success($partner);
    }

    /**
     * 新增商家
     */
    public function add(Request $request)
    {
        if ($request->method() !== 'POST') {
            return $this->error('请求方式错误');
        }

        $params = $request->post();
        
        // 验证必填参数
        if (empty($params['name'])) {
            return $this->error('商家名称不能为空');
        }
        if (empty($params['contact_phone'])) {
            return $this->error('联系电话不能为空');
        }
        if (empty($params['address'])) {
            return $this->error('地址不能为空');
        }
        if (empty($params['business_type_id'])) {
            return $this->error('请选择商家类型');
        }
        if (empty($params['service_level'])) {
            return $this->error('请选择服务等级');
        }

        // 创建商家
        try {
            $partner = new BusinessPartner();
            $partner->fill($params);
            $partner->status = $params['status'] ?? 1;
            $partner->sort = $params['sort'] ?? 0;
            $partner->save();

            return $this->success(['partner_id' => $partner->partner_id]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 编辑商家
     */
    public function edit(Request $request)
    {
        if ($request->method() !== 'POST') {
            return $this->error('请求方式错误');
        }

        $partner_id = $request->post('partner_id');
        if (!$partner_id) {
            return $this->error('参数错误');
        }

        $partner = BusinessPartner::find($partner_id);
        if (!$partner) {
            return $this->error('商家不存在');
        }

        $params = $request->post();
        
        // 验证必填参数
        if (empty($params['name'])) {
            return $this->error('商家名称不能为空');
        }
        if (empty($params['contact_phone'])) {
            return $this->error('联系电话不能为空');
        }
        if (empty($params['address'])) {
            return $this->error('地址不能为空');
        }
        if (empty($params['business_type_id'])) {
            return $this->error('请选择商家类型');
        }
        if (empty($params['service_level'])) {
            return $this->error('请选择服务等级');
        }

        try {
            $partner->fill($params);
            $partner->save();

            return $this->success(['partner_id' => $partner->partner_id]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 更新商家状态
     */
    public function status(Request $request)
    {
        if ($request->method() !== 'POST') {
            return $this->error('请求方式错误');
        }

        $partner_id = $request->post('partner_id');
        $status = $request->post('status');
        
        if (!$partner_id || !in_array($status, [0, 1])) {
            return $this->error('参数错误');
        }

        $partner = BusinessPartner::find($partner_id);
        if (!$partner) {
            return $this->error('商家不存在');
        }

        try {
            $partner->status = $status;
            $partner->save();
            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取服务等级文本
     */
    private function getServiceLevelText($level)
    {
        $levels = [
            'vip' => 'VIP商家',
            'normal' => '普通商家'
        ];
        return $levels[$level] ?? '';
    }

    /**
     * Alias for add method
     */
    public function create(Request $request)
    {
        return $this->add($request);
    }

    /**
     * Alias for all method
     */
    public function options(Request $request)
    {
        return $this->all($request);
    }

    /**
     * Alias for edit method
     */
    public function update(Request $request)
    {
        return $this->edit($request);
    }
} 